/*
 PureMVC AS3 Demo - Flex CafeTownsend
 Copyright (c) 2007-08 Michael Ramirez <michael.ramirez@puremvc.org>
 Parts Copyright (c) 2005-07 Adobe Systems, Inc. 
 Your reuse is governed by the Creative Commons Attribution 3.0 License
 */
package vn.demand.dragon.view
{
	import flash.events.Event;
	
	import flexed.widgets.alerts.alert;
	
	import mx.controls.Alert;
	import mx.events.CloseEvent;
	
	import org.puremvc.as3.interfaces.*;
	import org.puremvc.as3.patterns.mediator.Mediator;
	
	import vn.demand.dragon.CommonCommand;
	import vn.demand.dragon.MarketingApplicationFacade;
	import vn.demand.dragon.model.MasterdataProxy;
	import vn.demand.dragon.view.components.QuickCustomer;
	import vn.demand.dragon.view.components.QuotationForm;
	import vn.demand.utils.DpUtils;
    
    /**
     * A Mediator for interacting with the EmployeeList component
     */
    public class CompanyNewFormMediator extends Mediator implements IMediator
    {
        // Cannonical name of the Mediator
        public static const NAME:String = "CompanyNewFormMediator";

		private var companyProxy:CompanyProxy;
		private var masterdataProxy:MasterdataProxy;
        
        private var companyVO:Object;
        
        public static function makeId(companyVO:Object):String {
        	return NAME + "::" + companyVO.quote_code;
        }
        
        /**
         * Constructor. 
         */
        public function CompanyNewFormMediator(companyVO:Object, mediatorId:String, viewComponent:Object ) 
        {
            // pass the viewComponent to the superclass where 
            // it will be stored in the inherited viewComponent property
            super( mediatorId, viewComponent );
			
			companyForm.viewId = mediatorId;
			
			companyProxy = CompanyProxy( facade.retrieveProxy( mediatorId) );
			masterdataProxy = MasterdataProxy( facade.retrieveProxy( MasterdataProxy.NAME ) );
			
			companyForm.addEventListener(QuotationForm.QUOTATION_FORM_UI_CREATED, prepareData);
			companyForm.addEventListener(QuotationForm.SAVE_QUOTATION, onSaveQuotation);
			companyForm.addEventListener(QuotationForm.CHANGE_ON_QUOTATION_FORM, onChangeFormItem);
			companyForm.addEventListener(QuotationForm.CLOSE_QUOTATION_FORM, onCloseForm);
			companyForm.addEventListener(QuickCustomer.ADD_COMPANY, onAddCompany);
			
			this.companyVO = companyVO;
			
			companyForm.label = "" + companyVO.quote_code;
        }

		public function prepareData(event:Event):void {
			companyForm.quote_customer.dataProvider = masterdataProxy.customersDP;
			companyForm.quote_type.dataProvider = masterdataProxy.quotationTypesDP;
			companyForm.quote_currency.dataProvider = masterdataProxy.currenciesDP;
			
			companyForm.quote_type.selectedIndex = 0;
			companyForm.quote_currency.selectedIndex = 0;
			companyForm.quote_customer.selectedIndex = 0;
			companyForm.quote_status.text = 'Proposed';
			
			companyForm.canUnActive = false;
			companyForm.canComplete = false;
			companyForm.canEdit = true;
			companyForm.enableSave = true;
			companyForm.canActive = false;
		}

		public function onCloseForm(event:Event, needConfirm:Boolean=true):void {
			if (!needConfirm) {
	        	sendNotification(MarketingApplicationFacade.CLOSE_NEW_QUOTATION_PANEL, companyVO);
	        	return;
			}
			alert.confirm("Do you want to save?", handleConfirmSave, Alert.CANCEL);
        }
        
        public function handleConfirmSave(event:CloseEvent):void {
        	if (event.detail == Alert.CANCEL) {
        		return;
        	}
        	if (event.detail == Alert.NO) {
        		sendNotification(MarketingApplicationFacade.CLOSE_NEW_QUOTATION_PANEL, companyVO, "nosave");
        		return;
        	}
        	
        	doSaveQuotation();       		
        }

		public function onAddCompany(event:Event):void {
			var quickCompanyMediator:QuickCompanyMediator = facade.retrieveMediator(QuickCompanyMediator.NAME) as QuickCompanyMediator;
			quickCompanyMediator.show();
		}

		public function onChangeFormItem(event:Event):void {
			companyForm.enableSave = true;
		}
		
		public function onSaveQuotation(event:Event):void {
			doSaveQuotation();
		}
		public function doSaveCompany():Boolean {
			if (!doValidate()) {
				return false;
			}
			
			var company:Object = {};
			company.quote_status = 9;
            company.quote_code = companyVO.quote_code;
            company.quote_start_date = df.format(quotationForm.quote_start_date.selectedDate);
            company.quote_expire_date = df.format(quotationForm.quote_expire_date.selectedDate);
            company.quote_remarks = quotationForm.quote_remarks.text; 
            company.quote_customer = quotationForm.quote_customer.selectedData;
            company.quote_currency = quotationForm.quote_currency.selectedData;
            company.quote_type = quotationForm.quote_type.selectedData;
            
            companyVO = company;
			
			companyProxy.saveCompany(company);
			return true;
		}
		
		public function doValidate():Boolean {
			//pass validate
			var errors:String = "";
			if (Number(quotationForm.quote_customer.selectedData) == 0 || Number(quotationForm.quote_customer.selectedData) == NaN) {
				errors += "Please choose Customer\n";
			} 
			if (quotationForm.quote_start_date.selectedDate == null) {
				errors += "Please choose Valid From date\n";
			}
			if (quotationForm.quote_expire_date.selectedDate == null) {
				errors += "Please choose Valid To date\n";
			}
			if (DpUtils.compare(quotationForm.quote_start_date.selectedDate, quotationForm.quote_expire_date.selectedDate) < 0) {
				errors += "Valid From date must before Valid To date\n";
			}
			
			if (errors.length > 0) {
				alert.error(errors);
				return false;
			}
			return true;
		}
		

        /**
         * List all notifications this Mediator is interested in.
         * <P>
         * Automatically called by the framework when the mediator
         * is registered with the view.</P>
         * 
         * @return Array the list of Nofitication names
         */
        override public function listNotificationInterests():Array 
        {
            return [ 
            	MarketingApplicationFacade.QUOTATION_UPDATED,
            	MarketingApplicationFacade.QUOTATION_UPDATE_FAILED,
            	CommonCommand.COMPANY_ADDED
					 ];
        }

        /**
         * Handle all notifications this Mediator is interested in.
         * <P>
         * Called by the framework when a notification is sent that
         * this mediator expressed an interest in when registered
         * (see <code>listNotificationInterests</code>.</P>
         * 
         * @param INotification a notification 
         */
        override public function handleNotification( note:INotification ):void 
        {
        	if (note.getType() != getMediatorName()) {
        		return;
        	}
            switch ( note.getName() ) 
			{
				case MarketingApplicationFacade.QUOTATION_UPDATED:
					companyVO.quote_id = note.getBody().id;
					companyVO.real_code = note.getBody().code;
					RIALogger.debug(this, "Vua moi luu moi quotation, id: " + companyVO.quote_id);
					onCloseForm(new Event(""), false);
					break;
				case MarketingApplicationFacade.QUOTATION_UPDATE_FAILED:
					alert.error(note.getBody() as String);
					break;
					
                default:
                	break;
            }
        }
                    
        /**
         * Cast the viewComponent to its actual type.
         * 
         * <P>
         * This is a useful idiom for mediators. The
         * PureMVC Mediator class defines a viewComponent
         * property of type Object. </P>
         * 
         * <P>
         * Here, we cast the generic viewComponent to 
         * its actual type in a protected mode. This 
         * retains encapsulation, while allowing the instance
         * (and subclassed instance) access to a 
         * strongly typed reference with a meaningful
         * name.</P>
         * 
         * @return EmployeeList the viewComponent cast to EmployeeList
         */
        public function get customerForm():QuickCustomer
		{
            return viewComponent as QuickCustomer;
        }
		
//		private function logout( event:Event = null ):void
//		{
//			sendNotification( ApplicationFacade.APP_LOGOUT );
//		}
//		
//		private function addEmployee( event:Event = null ):void
//		{
//			sendNotification( ApplicationFacade.ADD_EMPLOYEE );
//		}
//		
//		private function updateEmployee( event:Event = null ):void
//		{
//			sendNotification( ApplicationFacade.UPDATE_EMPLOYEE, quotationList.employees_li.selectedItem);
//		}
    }
}